package main
import "net/http"
import (
	"demo_use/utils"
	"fmt"
	"strings"
	"os/exec"
	"math"
)


func Read(response http.ResponseWriter, req *http.Request){
	query := req.URL.Query()
	_,hasSearch := query["search"]
	if hasSearch {
		param := map[string]interface{}
		errMessage := ""
		_,page := query["page"]
		if !page {
			param["page"] = "1"
		}else{
			param["page"] = query["page"][0]
		}
		_,perPage := query["per_page"]
		if perPage{
			param["per_page"] = query["per_page"][0]
		}else{
			param["per_page"] = "100"
		}
		_,partId := query["part_id"]
		if partId {
			param["part_id"] = query["part_id"][0]
		}else {
			errMessage = errMessage+"part_id,"
		}
		_, gid := query["gid"]
		if gid {
		    param["gid"] = query["gid"][0]
		}else{
			errMessage = errMessage+"gid,"
		}
		_,sid := query["sid"]
		if sid{
			param["sid"] = query["sid"][0]
		}else{
			errMessage = errMessage+"sid,"
		}
		_,api := query["api"]
		if api{
			param["api"] = query["api"][0]
		}else{
			errMessage = errMessage+"api,"
		}
		_,beginTime := query["begin_time"]
		if beginTime {
			param["begin_time"] = query["begin_time"][0]
		}else{
			errMessage = errMessage+"begin_time,"
		}
		_,endTime := query["end_time"]
		if endTime {
			param["end_time"] = query["end_time"][0]
		}else{
			errMessage = errMessage+"end_time,"
		}
		if errMessage != ""{
			errMessage = errMessage[0:len(errMessage)-1]
			errMessage = errMessage+" is required"
			fmt.Fprintf(response,errMessage)
		}else{
			_,bmonth,bday := utils.StrToDate(param["begin_time"])
			eyear,emonth,eday := utils.StrToDate(param["end_time"])
			logDirYmd := ""
			if bmonth != emonth{
				logDirYmd  = fmt.Sprintf("./%s/%s/%s/%04d/*/*/",param["part_id"],param["gid"],param["sid"],eyear)
			}else if bday != eday{
				logDirYmd  = fmt.Sprintf("./%s/%s/%s/%04d/%02d/*/",param["part_id"],param["gid"],param["sid"],eyear,emonth)
			}else {
				logDirYmd = fmt.Sprintf("./%s/%s/%s/%04d/%02d/%02d/", param["part_id"], param["gid"], param["sid"], eyear, emonth, eday)
			}
			//请求参数
			whereStr := ""
			paramWhere := []string{}
			_,roleId := query["role_id"]
			if roleId {
				paramWhere = append(paramWhere," $5=="+query["role_id"][0])
			}
			if len(paramWhere)>0 {
				whereStr = " &&"+strings.Join(paramWhere," && ")
			}
			//http://192.168.71.21:8082/?search=1&page=1&gid=18&begin_time=2018-06-04&part_id=1000&end_time=2018-06-30&sid=s2&role_id=3
			//登录时间，角色id，角色等级，平台id，区服id，战力，登录ip,
			cmdTpl := "cat %s/%s_[0-9]*.txt |awk -F\" \" '{print $3}'|awk -F\",\" '{if($7>=%d && $7<=%d %s){print $0}else{}}'"
			cmd := fmt.Sprintf(cmdTpl,logDirYmd,param["api"],utils.Strtotime(param["begin_time"]),utils.Strtotime(param["end_time"]),whereStr)

			utils.FilePutContents("./debug.log",param["begin_time"]+"\n",true)
			utils.FilePutContents("./debug.log",logDirYmd+"\n",true)
			fmt.Fprintf(response, cmd)

			out, err := exec.Command("sh", "-c", cmd).Output()
			outStr := string(out)
			if err != nil{
				fmt.Fprintf(response,string(err.Error()))
			}else{
				fmt.Fprintf(response,outStr)
			}
			outArr := strings.Split(outStr,"\n")
			total := len(outArr)
			totalPage := math.Ceil(total/param["per_page"])
			offset := int(param["page"])-1
			data := []string{}
			if param["per_page"]<total {
				data = outArr[offset*param["per_page"],param["per_page"]]
			}else{
				data = outArr
			}
			//fmt.Fprintf(response,)
		}
		//utils.FilePutContents("./debug.log",string(year)+"\n",true)
		//utils.FilePutContents("./debug.log",string(month)+"\n",true)
		//utils.FilePutContents("./debug.log",string(day)+"\n",true)

		//fmt.Fprintf(response,string(year),string(month),string(day))
		//Logdir
		//logdirYmd  := fmt.Sprintf("./%s/%s/%s/%04d/%02d/%02d/",part_id,gid,sid,now.Year(),now.Month(),now.Day())
	}
}

func main(){
	http.HandleFunc("/",Read)
	http.ListenAndServe(":8082",nil)
}